/* file name  : JSlingCommon.java
 * created    : Sat 24 Sep 2005 12:55:43 AM EDT
 * authors    : Saikat Guha <saikat@cs.cornell.edu>
 * copyright  : GNU Lesser General Public License version 2.1 or later
 *
 * Copyright (C) 2005 Saikat Guha <saikat@cs.cornell.edu>
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation;
 * either version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307 USA
 *
 */
package net.nutss.signaling;

import java.net.*;
import java.util.regex.Pattern;
import java.util.Properties;
import java.io.FileInputStream;

/**
 * Common functionality used by the JSlingServer and JSlingProvider client.
 *
 * @author Saikat Guha
 * @version %I%, %G%
 */
class JSlingCommon {

    /**
    * Types of proxy resolution methods
     */
    private enum ProxyType { PROXY_JSTUNT, PROXY_DOMAIN, PROXY_FIXED};

    /**
    * Proxy resolution method
     */
    static ProxyType proxyType = ProxyType.PROXY_DOMAIN;;

    /**
    * Port the server listens on
     */
    static int proxyPort = 443;

    /**
    * Port the server listens on
     */
    static InetSocketAddress proxyFixedAddress = null;

    /**
     * Matches unsafe DNS characters
     */
    private static Pattern dnsUnsafe = Pattern.compile("(\\.|[^A-Za-z0-9.])+");

    /**
     * Initializes the JSling resolution framework
     */
    private static void init(String app) {
        try {
            String k;
            Properties config = new Properties();
            FileInputStream fis = new FileInputStream(app+".properties");
            config.load(fis);
            fis.close();

            k = config.getProperty("ProxyResolution");
            if (k != null)
                if (k.equalsIgnoreCase("JSTUNT"))
                    proxyType = ProxyType.PROXY_JSTUNT;
                else if (k.equalsIgnoreCase("DOMAIN"))
                    proxyType = ProxyType.PROXY_DOMAIN;
                else if (k.equalsIgnoreCase("FIXED"))
                    proxyType = ProxyType.PROXY_FIXED;

            k = config.getProperty("ProxyPort");
            if (k != null)
                proxyPort = Integer.parseInt(k);

            k = config.getProperty("ProxyAddress");
            if (k != null)
                proxyFixedAddress = new InetSocketAddress(InetAddress.getByName(k), proxyPort);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Formats an ID to a clean DNS address
     * @param id ID for which a proxy node is sought
     * @return DNS name for the ID
     */
    private static String dnsScrub(URI id) throws UnknownHostException {
        return "X"+dnsUnsafe.matcher(id.toString()).replaceAll(".") + "X";
    }

    /**
     * Returns the SocketAddress of the JSlingServer that maintains authoritative location information for
     * the given ID. Proxies are resolved through the JSTUNT NUTSS DNS hierarchy.
     * @param id ID for which a proxy node is sought
     * @return IP address and port of the proxy
     * @throws UnknownHostException if proxy cannot be found
     */
    private static SocketAddress resolveProxyJSTUNT(URI id) throws UnknownHostException {
        return new InetSocketAddress(InetAddress.getByName(dnsScrub(id)+".jstunt.nutss.net"), proxyPort);
    }

    /**
     * Returns the SocketAddress of the JSlingServer that maintains authoritative location information for
     * the given ID. Proxies are resolved through individual domain hierarchies.
     * @param id ID for which a proxy node is sought
     * @return IP address and port of the proxy
     * @throws UnknownHostException if proxy cannot be found
     */
    private static SocketAddress resolveProxyDomain(URI id) throws UnknownHostException {
        return new InetSocketAddress(InetAddress.getByName(id.toString().split("@")[1]), proxyPort);
    }

    /**
     * Returns the SocketAddress of the JSlingServer that maintains authoritative location information for
     * the given ID. Proxies are resolved to a fixed address.
     * @param id ID for which a proxy node is sought
     * @return IP address and port of the proxy
     * @throws UnknownHostException if proxy cannot be found
     */
    private static SocketAddress resolveProxyFixed(URI id) throws UnknownHostException {
        return proxyFixedAddress;
    }

    /**
     * Returns the SocketAddress of the JSlingServer that maintains authoritative location information for
     * the given ID.
     * @param id ID for which a proxy node is sought
     * @return IP address and port of the proxy
     * @throws UnknownHostException if proxy cannot be found
     */
    static SocketAddress resolveProxy(URI id) throws UnknownHostException {
        switch (proxyType) {
            case PROXY_JSTUNT: return resolveProxyJSTUNT(id);
            case PROXY_DOMAIN: return resolveProxyDomain(id);
            case PROXY_FIXED: return resolveProxyFixed(id);
            default: throw new UnknownHostException("Don't know how to resolve: "+id);
        }
    }

    static {
        //init("");
    }

}
